from django.core.management.base import BaseCommand, CommandError
from django.conf import settings
from utils.image_utils import ImageProcessor
import os
import logging

logger = logging.getLogger('api')

class Command(BaseCommand):
    help = '将媒体目录中的图像转换为WebP格式并压缩'

    def add_arguments(self, parser):
        parser.add_argument(
            '--directory',
            type=str,
            help='要处理的目录路径，默认为MEDIA_ROOT',
        )
        parser.add_argument(
            '--target-size',
            type=int,
            default=50,
            help='目标文件大小（KB），默认为50KB',
        )
        parser.add_argument(
            '--delete-original',
            action='store_true',
            help='转换后删除原始文件',
        )

    def handle(self, *args, **options):
        try:
            directory = options['directory'] or settings.MEDIA_ROOT
            target_size = options['target_size']
            delete_original = options['delete_original']
            
            self.stdout.write(f"开始处理目录: {directory}")
            self.stdout.write(f"目标文件大小: {target_size}KB")
            
            # 确保目录存在
            if not os.path.exists(directory):
                raise CommandError(f"目录不存在: {directory}")
            
            # 初始化处理器
            processor = ImageProcessor()
            
            # 批量处理目录
            from pathlib import Path
            directory_path = Path(directory)
            
            # 图像文件扩展名
            image_extensions = {'.jpg', '.jpeg', '.png', '.gif', '.bmp'}
            
            # 计数器
            processed = 0
            skipped = 0
            error = 0
            
            # 遍历目录中的所有文件
            for file_path in directory_path.glob('**/*'):
                if file_path.is_file() and file_path.suffix.lower() in image_extensions:
                    try:
                        # 构建新文件名
                        new_path = file_path.with_suffix('.webp')
                        
                        # 如果新文件已存在，则跳过
                        if new_path.exists():
                            self.stdout.write(f"跳过已存在的文件: {new_path}")
                            skipped += 1
                            continue
                        
                        # 压缩并转换图像
                        self.stdout.write(f"处理文件: {file_path}")
                        compressed_image = processor.compress_image(
                            str(file_path),
                            output_format='WEBP',
                            target_size_kb=target_size
                        )
                        
                        # 保存新文件
                        with open(new_path, 'wb') as f:
                            f.write(compressed_image.getvalue())
                        
                        self.stdout.write(f"成功转换: {file_path} -> {new_path}")
                        processed += 1
                        
                        # 如果设置了删除原文件选项
                        if delete_original:
                            file_path.unlink()
                            self.stdout.write(f"已删除原文件: {file_path}")
                            
                    except Exception as e:
                        self.stderr.write(f"处理文件 {file_path} 时出错: {str(e)}")
                        error += 1
            
            # 输出统计信息
            self.stdout.write(self.style.SUCCESS(
                f"处理完成! 成功: {processed}, 跳过: {skipped}, 错误: {error}"
            ))
            
        except Exception as e:
            raise CommandError(f"转换图像时出错: {str(e)}") 